package com.finger.forest.http;

import android.annotation.SuppressLint;
import android.util.Log;


import com.finger.forest.base.BaseApi;
import com.finger.forest.http.json.JsonConverterFactory;
import com.finger.forest.utils.NetUtil;
import com.finger.forest.utils.ToastUtils;

import java.util.concurrent.TimeUnit;

import io.reactivex.Maybe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.CacheControl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

/**
 * Api service
 * Created by ***** on 2020/4/26.
 */

public class Api {

    private int maxStale = 60 * 60 * 24;
    private static final String PLATFORM = "android";

    public static OkHttpClient.Builder client() {
        OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();

        httpClientBuilder.connectTimeout(30, TimeUnit.SECONDS);
        httpClientBuilder.writeTimeout(30, TimeUnit.SECONDS);
        httpClientBuilder.readTimeout(30, TimeUnit.SECONDS);

        addCheckNetworkChain(httpClientBuilder);

        httpClientBuilder.networkInterceptors()
                .add(chain -> {
                    Request.Builder req = chain.request().newBuilder();
                    req.addHeader("Accept-Charset", "utf-8")
                            .addHeader("Connection", "keep-alive")
                            .addHeader("Accept", "*/*")
                            .addHeader("client_version", "1.0.0")//版本号
                            .addHeader("device_type", PLATFORM)//客户端类型
                            .addHeader("device_id", PLATFORM)//设备id
                            .addHeader("client_id", "app")
                            .addHeader("client_secret", "app");

//                    addAuthorizationHeader(req);

                    Log.e("header", req.build().headers().toString());
                    Response response = chain.proceed(req.build());
                    return response.newBuilder().build();
                });
        httpClientBuilder.addInterceptor(
                new HttpLoggingInterceptor().setLevel(
                        HttpLoggingInterceptor.Level.BODY
                )
        );

//        httpClientBuilder.addNetworkInterceptor(chain -> {
//            /*
//             * 接口字段返回 拦截器
//             * */
//            Charset UTF8 = Charset.forName("UTF-8");
//            Response response = chain.proceed(chain.request());
//            ResponseBody responseBody = response.body();
//            Log.d("response", response.toString());
//            String resultsBody = null;
//            if (HttpHeaders.hasBody(response)) {
//                BufferedSource source = responseBody.source();
//                source.request(Long.MAX_VALUE); // Buffer the entire body.
//                Buffer buffer = source.buffer();
//
//                Charset charset = UTF8;
//                MediaType contentType = responseBody.contentType();
//                if (contentType != null) {
//                    try {
//                        charset = contentType.charset(UTF8);
//                    } catch (UnsupportedCharsetException e) {
//                        e.printStackTrace();
//                    }
//                }
//                resultsBody = buffer.clone().readString(charset);
//            }
//
//            try {
//                if (resultsBody != null && !TextUtils.isEmpty(resultsBody)) {
//                    Gson gson = new Gson();
//                    BaseEntity requestLoginBean = gson.fromJson(resultsBody, BaseEntity.class);
//
//                    if (requestLoginBean.getResp_code() == 0){
//
//                    }
//
//                    if (requestLoginBean.getResp_code() == -2) {
//                        if (FastDataUtils.getToken() != null && !TextUtils.isEmpty(FastDataUtils.getToken())) {
//                            FastDataUtils.setToken("");
//                            EventBus.getDefault().post(new FinishEvent());
//                            LoginActivity.open(BaseApplication.getInstance());
//                        } else {
//                            Log.e("TAG", "--------走这了--------");
//                            EventBus.getDefault().post(new FinishEvent());
//                            LoginActivity.open(BaseApplication.getInstance());
//                        }
//                    }
//                }
//
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//
//
//            return response;
//        });

        return httpClientBuilder;
    }

    //服务器IP
    public static String SERVER_IP = "36.7.152.42";
    //服务器端口
    public static String SERVER_PORT = "9090";

    public RetrofitJavaService apiService() {
        Retrofit.Builder retrofitBuilder = new Retrofit.Builder();

        Retrofit retrofit = retrofitBuilder
                //.baseUrl(BaseApi.BASE_URL)
                .baseUrl("http://"+ SERVER_IP +":"+SERVER_PORT+"/")
                .client(client().build())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io()))
                .addConverterFactory(GsonDConverterFactory.create())
                .build();
        return retrofit.create(RetrofitJavaService.class);
    }

    private static Retrofit initRetrofit() {
        return new Retrofit.Builder()
                .baseUrl(BaseApi.BASE_URL)
                .addConverterFactory(JsonConverterFactory.create())
                .client(client().build())
                .build();
    }


    protected static void addCheckNetworkChain(OkHttpClient.Builder httpClientBuilder) {
        httpClientBuilder.addInterceptor(chain -> {

            Request request = chain.request();
            if (!NetUtil.isNetworkAvailable()) {

                Maybe.just("没有可用网络, 请连接网络后重试")
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(ToastUtils::show, throwable -> {
                            Log.e("Debug", "error", throwable);
                        });

                // @notice  由于服务器不支持缓存，所以这里其实是没有起作用，等服务器起作用就可以了
                request = request.newBuilder()
                        .cacheControl(CacheControl.FORCE_CACHE)
                        .build();
            }

            return chain.proceed(request)
                    .newBuilder()
                    .build();
        });
    }

//    public static void addAuthorizationHeader(Request.Builder req) {
//        String authorizationHeader = FastDataUtils.getToken();
//        if (!TextUtils.isEmpty(authorizationHeader) || !authorizationHeader.equals("")) {
//            Log.e("token", authorizationHeader);
//            authorizationHeader = String.format(Locale.CHINA, "Bearer %s", FastDataUtils.getToken());
//            req.addHeader("Authorization", authorizationHeader);
//            Log.e("TAG", "=========" + authorizationHeader);
//        } else {
////            req.addHeader("Authorization", "Basic bGc6YmFyQExn");
//        }
//    }

    static Api api = null;

    public static RetrofitJavaService getInstanceGson() {

        if (api == null) {
            api = new Api();
        }
        return api.getService();
    }

    public RetrofitJavaService getService() {
        return apiService();
    }

}
